/*
 * Copyright (C), 2015-2018
 * FileName: WebSocketFrameEncoder
 * Author:   zhao
 * Date:     2018/8/13 17:12
 * Description: WebSocketFrameEncoder编码器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.loveprogrammer.base.codec;

import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.pojo.StringMessage;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @ClassName IMessageToWebSocketFrameEncoder
 * @Description websocket消息编码器
 * @Author admin
 * @Date 2024/2/29 16:53
 * @Version 1.0
 */
public class IMessageToWebSocketFrameEncoder extends MessageToMessageEncoder<StringMessage> {
  @Override
  protected void encode(ChannelHandlerContext channelHandlerContext, StringMessage msg, List<Object> list)
          throws Exception {
    //组合缓冲区
    CompositeByteBuf byteBuf = Unpooled.compositeBuffer();

    String body = msg.getBody();
    byte[] bodyBytes = body.getBytes(Charset.forName(ConstantValue.PROJECT_CHARSET));
    byteBuf.writeInt(msg.getTopicId());
    byteBuf.writeInt(msg.getTagId());
    byteBuf.writeInt(msg.getStatusCode());
    byteBuf.writeInt(bodyBytes.length);
    byteBuf.writeBytes(bodyBytes);

    list.add(new BinaryWebSocketFrame(byteBuf));
  }
}
